//
//  SafeWall.swift
//  agent-iOS
//
//  Created by miao on 2021/3/23.
//  Copyright © 2021 深圳市看房网科技有限公司. All rights reserved.
//

import Foundation
import WebKit

public typealias VerifyCallback = (_ success: Bool, [String: Any]?) -> Void
public class SafeWall: NSObject {
    
    private var anchorView: UIView
    private var appid: String
    private var verifyCallback: VerifyCallback
    
    lazy var webView: WKWebView = {
        let configuration = WKWebViewConfiguration()
        configuration.userContentController = WKUserContentController()
        
        //注册果断回调方法
        configuration.userContentController.add(self, name: "loadAction")
        configuration.userContentController.add(self, name: "errorAction")
        configuration.userContentController.add(self, name: "verifiedAction")
        let webView = WKWebView.init(frame:CGRect(x: 0, y: 0, width: anchorView.frame.size.width, height: anchorView.frame.size.height), configuration: configuration)
        webView.navigationDelegate = self
        webView.isOpaque = false
        webView.backgroundColor = .clear
        webView.scrollView.backgroundColor = .clear
        return webView
    }()
    
    /// 接口保护，腾讯防水墙
    /// - view: 添加webView的父类View
    /// - appid: 腾讯防水墙的应用ID
    /// - onCompletion：验证通过
    /// 需要自己管理父类View的生命周期
    public init?(onView view: UIView, appid: String, onCompletion:@escaping VerifyCallback) {
        let width = view.bounds.width
        let height = view.bounds.height
        if width < 261 || height < 261 {
            print("腾讯防水墙初始化失败，添加防水墙容器的宽度和高度不能小于261！！！")
            return nil
        }
        
        self.appid = appid
        anchorView = view
        verifyCallback = onCompletion
        super.init()
    }
    
    public func load() {
        if #available(iOS 11.0, *) {
            webView.scrollView.contentInsetAdjustmentBehavior = .never
        }
        anchorView.addSubview(webView)
        let html =
            """
            <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <title></title> <script src="https://ssl.captcha.qq.com/TCaptcha.js?"></script> </head> <body> <script type="text/javascript"> (function(){ window.SDKTCaptchaVerifyCallback = function (retJson) { if (retJson){ window.webkit.messageHandlers.verifiedAction.postMessage(retJson) } }; window.SDKTCaptchaReadyCallback = function (retJson) { if (retJson && retJson.sdkView && retJson.sdkView.width && retJson.sdkView.height && parseInt(retJson.sdkView.width) >0 && parseInt(retJson.sdkView.height) >0 ){ window.webkit.messageHandlers.loadAction.postMessage(retJson) } }; window.onerror = function (msg, url, line, col, error) { if (window.TencentCaptcha == null) { window.webkit.messageHandlers.errorAction.postMessage(error) } }; var sdkOptions = {}; sdkOptions.ready = window.SDKTCaptchaReadyCallback; window.onload = function () { new TencentCaptcha("\(self.appid))", SDKTCaptchaVerifyCallback, sdkOptions).show(); }; })(); </script></body></html>
            """
        webView.loadHTMLString(html, baseURL: nil)
    
//        webView.load(URLRequest(url: URL(fileURLWithPath: Bundle.main.path(forResource: "test", ofType: "html")!)))
    }
}

extension SafeWall: WKScriptMessageHandler, WKNavigationDelegate {
    public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
        if anchorView.bounds.size.width != UIScreen.main.bounds.size.width {
            self.webView.evaluateJavaScript("document.getElementById('t_mask').style.background='#FFFFFF'", completionHandler: nil)
        }
    }
    
    public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
            //加载成功, 更新webview的frame
            if message.name == "loadAction" {
                if let jsData =  message.body as? [String: Any], let sdkView = jsData["sdkView"] as? [String:
                    CGFloat], let width = sdkView["width"], let height = sdkView["height"] {
                    print(jsData)
    //                let temp = anchorView.bounds.size.width - width
    //                let temp2 = anchorView.bounds.size.height - height
    //                webView.frame = CGRect(x: temp/2, y: temp2/2, width: width, height: height)
                }
            }
            //划动验证
            else if message.name == "verifiedAction" {
                if let jsData =  message.body as? [String: Any], let ret = jsData["ret"] as? Int {
                    //验证成功
                    if ret == 0 {
                        verifyCallback(true,jsData)
                        webView.removeFromSuperview()
                    }
                    //点击关闭
                    else {
                        verifyCallback(false,jsData)
                        webView.removeFromSuperview()
                    }
                }
            }
            //加载失败
            else if message.name == "errorAction" {
                verifyCallback(false,nil)
                webView.removeFromSuperview()
            }
            else{
                
            }
        }
}

